package com.ruoyi.business.controller;

import com.ruoyi.business.domain.*;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author win43
 */
@Api("业务前端接口")
@RestController
@RequestMapping("/business")
public class BusinessFrontController extends BaseController {

    @Autowired
    private IContentService contentService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private IStatisticsService statisticsService;

    @Autowired
    private IDepartService departService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 根据位置编码获取指定位置的一级栏目
     * 主导航栏、飘窗                                                     根据位置查询出一级后，点击链接进入列表页，根据链接的categoryId查询其子级列表及列表中的内容信息
     * 主导航栏    最多二级栏目
     * 飘窗      最多一级栏目
     * 主页               建立主页栏目后，屏蔽主页栏目菜单                   主页栏目不可编辑，栏目是固定的，根据categoryId查询出对应栏目的信息，及其子级列表及列表中的内容信息
     * 专题专栏 最多三级栏目
     * 其他栏目 最多只能二级栏目
     * 轮播图、头条        建立轮播图、头条栏目后，屏蔽轮播图、头条栏目菜单     轮播图、头条栏目不可编辑，栏目是固定的，根据categoryId查询出对应栏目的信息，及其子级列表及列表中的内容信息
     * <p>
     * 主导航栏    2
     * 飘窗       1
     * 主页
     * 专题  3
     * 其他  2
     */
    @ApiOperation("获取某位置的所有顶级栏目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "position", value = "位置信息，1 主导航栏栏目, 2 主页栏目, 3 飘窗栏目, 4 轮播图栏目, 5 头条栏目"),
    })
    @GetMapping("/getCategoriesByPosition/{position}")
    public AjaxResult getCategoriesByPosition(@PathVariable Integer position) {
        List<Category> categories =
                categoryService.selectCategoryList(new Category().setPosition(position).setParentId(0L).setStatus(1));
        return AjaxResult.success(categories);
    }

    @ApiOperation("获取栏目信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "栏目id"),
    })
    @GetMapping("/getCategoryById/{id}")
    public AjaxResult getCategoryById(@PathVariable Long id) {
        Category category = categoryService.selectCategoryById(id);
        return AjaxResult.success(category);
    }

    /**
     * 根据栏目id获取栏目信息 及 内容信息
     * 用于主页各栏目、轮播图、头条、列表页 点击侧边栏、分页
     */
    @ApiOperation("获取某栏目下的所有内容, 主页的分页参数需要根据主页要展示的数据条数进行各自指定，列表页的分页参数可各自去指定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "栏目id"),
    })
    @GetMapping("/getContentsByCategoryId/{categoryId}")
    public TableDataInfo getContentsByCategoryId(@PathVariable long categoryId) {
        Category category = categoryService.selectCategoryById(categoryId);
        List<Category> allList =
                categoryService.selectCategoryList(new Category().setStatus(1));
        ArrayList<Category> categories = new ArrayList<>();
        categoryService.queryChildrenList(allList, categories, category);
        categories.add(category);
        List<Long> categoryIds = categories.stream().map(Category::getId).collect(Collectors.toList());

        startPage();
        List<Content> contentList = contentService.selectContentListByCategoryIds(categoryIds);
        return getDataTable(contentList);
    }

    /**
     * 根据传入的category_id获取子级category
     * 用于列表页侧边导航栏、主页部分二级导航
     */

    @ApiOperation("获取某栏目下的所有子级栏目")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "栏目id"),
    })
    @GetMapping("/getChildrenCategories/{categoryId}")
    public AjaxResult getChildrenCategories(@PathVariable long categoryId) {
        List<Category> allList =
                categoryService.selectCategoryList(new Category().setStatus(1));
        Category category = categoryService.selectCategoryById(categoryId);

        Category targetCategory = categoryService.queryTree(allList, category);
        return AjaxResult.success(targetCategory);
    }

    @ApiOperation("获取内容详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "内容id"),
    })
    @GetMapping("/getContentInfo/{id}")
    public AjaxResult getContentInfo(@PathVariable long id) {
        Content content = contentService.selectContentById(id);

        String belongName = sysDictDataService.selectDictLabel("business_belong", content.getBelong().toString());
        content.setBelongName(belongName);

        Integer count = statisticsService.countVisitByContentId(id);
        content.setCount(count);
        return AjaxResult.success(content);
    }

    /**
     * 根据content_id统计内容点击量
     */
    @GetMapping("/contentStatistics")
    public AjaxResult contentStatistics(long contentId) {
        return null;
    }

    /**
     * 主页专用
     * 抽取所有主页栏目，根据不同栏目抽取不同数量内容
     */
    @GetMapping("/getIndexContents")
    public AjaxResult getIndexContent() {
        List<Category> indexCategories =
                categoryService.selectCategoryList(new Category().setPosition(2).setParentId(0L).setStatus(1));
        List<Category> swiperCategories =
                categoryService.selectCategoryList(new Category().setPosition(4).setParentId(0L).setStatus(1));
        List<Category> topCategories =
                categoryService.selectCategoryList(new Category().setPosition(5).setParentId(0L).setStatus(1));

        List<Category> categories = new ArrayList<>();
        categories.addAll(indexCategories);
        categories.addAll(swiperCategories);
        categories.addAll(topCategories);

        categories.forEach(item -> {
            if ( item.getId() == 1405732324212998144L || item.getId() == 1405732774685442048L || item.getId() == 1405732743567900672L ) {
                // 专题专栏   全国网站   重要站点
                List<Category> childList =
                        categoryService.selectCategoryList(new Category().setStatus(1).setParentId(item.getId()));
                item.setChildren(childList);
            } else {
                Category category = categoryService.selectCategoryById(item.getId());
                List<Category> allList = categoryService.selectCategoryList(new Category().setStatus(1));
                ArrayList<Category> children = new ArrayList<>();
                categoryService.queryChildrenList(allList, children, category);
                children.add(category);
                List<Long> categoryIds = children.stream().map(Category::getId).collect(Collectors.toList());
                List<Content> contents = null;
                if (item.getId().equals(1405728675059466240L)) {
                    // 轮播图
                    contents = contentService.selectContentListByCategoryIds(categoryIds, 5);
                } else if (item.getId().equals(1405728732211052544L)) {
                    // 头条
                    contents = contentService.selectContentListByCategoryIds(categoryIds, 8);
                } else {
                    // 普通
                    contents = contentService.selectContentListByCategoryIds(categoryIds, 6);
                }
                item.setContents(contents);
            }
        });
        return AjaxResult.success(categories);
    }

    @GetMapping("/addStatistics/{contentId}")
    public AjaxResult addStatistics(@PathVariable Long contentId, HttpServletRequest request){
        String clientIp = IpUtils.getIpAddr(request);
        Statistics statistics = new Statistics();
//        boolean has =  statisticsService.hasTodayStatistics(contentId, clientIp);
//        if ( has ) {
//            return AjaxResult.success("今日您已阅读过该篇文章");
//        }else {
            Staff staff = staffService.selectStaffByIp(clientIp);
            if (staff != null) {
                statistics.setClientDepartId(staff.getDepartId());
                statistics.setClientStaffId(staff.getId());
                statistics.setClientBelong(Integer.parseInt(staff.getBelong().toString()));
            }
            statistics.setClientIp(clientIp);
            statistics.setContentId(contentId);
            statisticsService.insertStatistics(statistics);

            return AjaxResult.success("这篇文章您已阅读");
//        }
    }

    @GetMapping("/parentNames/{categoryId}")
    public AjaxResult findParentNames(@PathVariable Long categoryId){
        List<Category> allList = categoryService.selectCategoryList(new Category().setStatus(1));
        Category category = categoryService.selectCategoryById(categoryId);
        ArrayList<Map<String, Object>> names = new ArrayList<>();
        categoryService.queryParentNames(allList, category, names);

        System.out.println(names);

        return AjaxResult.success(names);
    }

    /**
     * 发布
     * @return
     */
    @GetMapping("/statisticsPublish")
    public AjaxResult statisticsPublish(){
        return AjaxResult.success(statisticsService.selectPublishStatistics());
    }

    /**
     * 浏览
     * 热点
     *
     * @return
     */
    @GetMapping("/statisticsVisits/{limit}")
    public AjaxResult statisticsVisits(@PathVariable Integer limit){

        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("business_belong");
        List<SysDictData> belongs = sysDictDataService.selectDictDataList(sysDictData);

        List<Map<String, Object>> result = belongs.stream().map(belong -> {
            List<Depart> departList = statisticsService.selectDepartStatistics(10,
                    Integer.parseInt(belong.getDictValue()));
            departList.forEach(depart -> {
                Depart res = departService.selectDepartById(depart.getId());
                depart.setName(res.getName());
            });
            return new HashMap<String, Object>() {{
                put("belongName", belong.getDictLabel());
                put("departList", departList);
            }};
        }).collect(Collectors.toList());

        return AjaxResult.success(result);
    }

    @GetMapping("/statisticsHots/{limit}")
    public AjaxResult statisticsHots(@PathVariable Integer limit){
        List<Content> contents = statisticsService.selectContentStatistics(limit);

        contents.forEach(item -> {
            Content content = contentService.selectContentById(item.getId());
            if ( content != null) {
                String belongName = sysDictDataService.selectDictLabel("business_belong", content.getBelong().toString());
                item.setBelongName(belongName);

                item.setTitle(content.getTitle());
                item.setCreateTime(content.getCreateTime());
                item.setDepartName(content.getDepartName());
                item.setType(content.getType());
            }
        });

        return AjaxResult.success(contents);
    }

    @GetMapping("/statisticsHotsList")
    public TableDataInfo statisticsHotsList(){
        startPage();
        List<Content> contents = statisticsService.selectContentStatisticsPage();

        contents.forEach(item -> {
            Content content = contentService.selectContentById(item.getId());
            if ( content != null) {
                String belongName = sysDictDataService.selectDictLabel("business_belong", content.getBelong().toString());
                item.setBelongName(belongName);

                item.setTitle(content.getTitle());
                item.setCreateTime(content.getCreateTime());
                item.setDepartName(content.getDepartName());
                item.setType(content.getType());
            }
        });

        return getDataTable(contents);
    }

    /**
     * 获取归属及其部门的树
     * @return
     */
    @GetMapping("/departWithBelong")
    public AjaxResult departWithBelong(){
        List<DepartVO> departVOS = departService.selectDepartTree();
        return AjaxResult.success(departVOS);
    }

    /**
     * 获取某部门发文统计
     * @param departId
     * @return
     */
    @GetMapping("/departStatisticsVisit/{departId}")
    public AjaxResult departStatisticsVisit(@PathVariable Long departId){
        List<Content> contents = statisticsService.selectContentsByDepartId(departId);
        return AjaxResult.success(contents);
    }

    @GetMapping("/getContentByDepartId/{departId}")
    public TableDataInfo getContentByDepartId(@PathVariable Long departId){
        startPage();
        List<Content> contents = contentService.selectContentListByDepartId(departId);
        return getDataTable(contents);
    }

    @ApiOperation("测试")
    @GetMapping("/test")
    public AjaxResult test(){
        Staff staff = staffService.selectStaffByIp("127.0.0.1");
        return AjaxResult.success(staff);
    }
}

